#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <pthread.h>
using namespace std;

int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // 定义并初始化锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;   // 定义并初始化条件变量

void *route(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        // 对临界区上锁
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            // 在条件变量下等待
            pthread_cond_wait(&cond, &lock);
            cout << name << ":sells ticket:" << ticket << endl;
            ticket--;
            // 结束访问临界区，解锁
            pthread_mutex_unlock(&lock);
        }
        else
        {
            // 结束访问临界区，解锁
            pthread_mutex_unlock(&lock);
            break;
        }
    }

    return nullptr;
}

int main()
{
    while (1)
    {
        pthread_t t1, t2, t3, t4;
        pthread_create(&t1, NULL, route, (void *)"thread 1");
        pthread_create(&t2, NULL, route, (void *)"thread 2");
        pthread_create(&t3, NULL, route, (void *)"thread 3");
        pthread_create(&t4, NULL, route, (void *)"thread 4");

        while (1)
        {
            // 每个一秒唤醒一个线程
            sleep(1);
            pthread_cond_signal(&cond);
        }

        pthread_join(t1, NULL);
        pthread_join(t2, NULL);
        pthread_join(t3, NULL);
        pthread_join(t4, NULL);
    }
}